package org.jeecg.modules.demo.crm.glm.util;

import org.jeecg.common.util.MinioUtil;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream; // Import for ByteArrayInputStream
import java.io.ByteArrayOutputStream; // Import for ByteArrayOutputStream

// Apache PDFBox 依赖 (需要在你的 pom.xml 中添加)
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

public class PdfToImageUploader {

    /**
     * 自定义的 MultipartFile 实现，避免依赖 spring-test
     */
    static class CustomMultipartFile implements MultipartFile {
        private final String name;
        private final String originalFilename;
        private final String contentType;
        private final byte[] content;

        public CustomMultipartFile(String name, String originalFilename, String contentType, byte[] content) {
            this.name = name;
            this.originalFilename = originalFilename;
            this.contentType = contentType;
            this.content = content;
        }

        @Override
        public String getName() {
            return name;
        }

        @Override
        public String getOriginalFilename() {
            return originalFilename;
        }

        @Override
        public String getContentType() {
            return contentType;
        }

        @Override
        public boolean isEmpty() {
            return content == null || content.length == 0;
        }

        @Override
        public long getSize() {
            return content.length;
        }

        @Override
        public byte[] getBytes() throws IOException {
            return content;
        }

        @Override
        public InputStream getInputStream() throws IOException {
            return new ByteArrayInputStream(content);
        }

        @Override
        public void transferTo(File dest) throws IOException, IllegalStateException {
            throw new UnsupportedOperationException("This custom MultipartFile does not support transferTo(File dest).");
        }
    }




    /**
     * 从PDF URL获取文件，转换为图片并上传到MinIO
     *
     * @param pdfUrl PDF文件的URL地址
     * @param bizPath MinIO上传的业务路径
     * @return 上传到MinIO的图片URL列表
     * @throws Exception 如果在下载、转换或上传过程中发生错误
     */
    public static String convertPdfAndUploadImages(String pdfUrl, String bizPath) throws Exception {
        // 1. 从URL下载PDF文件
        InputStream pdfInputStream = null;
        PDDocument document = null;
        try {
            URL url = new URL(pdfUrl);
            pdfInputStream = url.openStream();
            document = PDDocument.load(pdfInputStream);

            // 2. 将PDF的每一页转换为图片
            PDFRenderer pdfRenderer = new PDFRenderer(document);
            int pageCount = document.getNumberOfPages();
            if(pageCount > 0){
                BufferedImage image = pdfRenderer.renderImageWithDPI(0, 300); // 300 DPI 分辨率
                // 将BufferedImage转换为 byte[]
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                try {
                    ImageIO.write(image, "png", baos); // 将图片写入 ByteArrayOutputStream
                } finally {
                    baos.close();
                }
                byte[] imageBytes = baos.toByteArray();
                // 创建自定义的 MultipartFile 对象
                String originalFilename = "page_" + (0 + 1) + ".png";
                MultipartFile multipartFile = new CustomMultipartFile(
                        "file",           // field name for the file, often "file"
                        originalFilename, // original file name
                        "image/png",      // content type
                        imageBytes        // file content as byte array
                );
                // 3. 上传图片到MinIO
                String uploadedUrl =MinioUtil.upload(multipartFile, bizPath);
                return uploadedUrl;
            }
        } finally {
            if (document != null) {
                try {
                    document.close();
                } catch (IOException e) {
                    System.err.println("关闭 PDF 文档时出错 " + e.getMessage());
                }
            }
            if (pdfInputStream != null) {
                try {
                    pdfInputStream.close();
                } catch (IOException e) {
                    System.err.println("关闭 PDF 输入流时出错: " + e.getMessage());
                }
            }
        }
        return null;
    }

   /* public static void main(String[] args) {
        String pdfUrl = "http://154.201.66.67:9000/blithe-crm/temp/2025-0625_1750786753296.pdf";
        String bizPath = "pdf-images/"; // 你希望上传到MinIO的业务路径

        try {
            List<String> uploadedImageUrls = convertPdfAndUploadImages(pdfUrl, bizPath);
            System.out.println("Uploaded image URLs:");
            for (String url : uploadedImageUrls) {
                System.out.println(url);
            }
        } catch (Exception e) {
            System.err.println("Failed to convert PDF and upload images: " + e.getMessage());
            e.printStackTrace();
        }
    }*/
}